﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp4
{
   
    public partial class MainWindow : Window
    {
        private Suspension_Keyboard keyboardWindow;//keyboardWindow：悬浮键盘窗口（Suspension_Keyboard类型）的实例变量，用于控制键盘窗口的创建、显示和关闭
        private MainViewModel viewModel;
        private TextBox currentFocusedTextBox;


        public MainWindow()
        {
            InitializeComponent();
            viewModel = (MainViewModel)DataContext;//DataContext它是一个对象，能够当作数据绑定的源。借助把 DataContext 设置成一个具体的视图模型（ViewModel），
            viewModel = new MainViewModel();       //就可以让界面元素（像 TextBox 之类的）绑定到视图模型里的属性，从而达成数据的自动同步。
            DataContext = viewModel;


        }



                                              

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)//TextBox_GotFocus 事件（文本框获得焦点时触发）//GotFocus="TextBox_GotFocus"
        { // 1. 记录当前获得焦点的TextBox
            currentFocusedTextBox = (TextBox)sender;// sender是触发事件的TextBox，强转为TextBox类型
            if (keyboardWindow == null)// 2. 检查悬浮键盘窗口是否已创建
            {
                keyboardWindow = new Suspension_Keyboard(); // 若未创建，则新建悬浮键盘窗口
                keyboardWindow.CurrentTextBox = currentFocusedTextBox; // 将当前聚焦的TextBox传递给键盘窗口（让键盘知道要操作哪个文本框)
                                    // 获取当前 TextBox 的位置和大小
                Point position = currentFocusedTextBox.PointToScreen(new Point(0, 0));//当前textbox的位置坐标
                double left = position.X;
                double top = position.Y;//+ currentFocusedTextBox.ActualHeight;//当前textBox的高度

                // 设置悬浮键盘窗口的位置
                keyboardWindow.Left = left;
                keyboardWindow.Top = top;

           
                keyboardWindow.Show();// 显示悬浮键盘
            }
            else
            {
                keyboardWindow.CurrentTextBox = currentFocusedTextBox;
            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (keyboardWindow != null)
            {
             
                keyboardWindow.Close();
                keyboardWindow = null;
            }
        }
    }
}